#include "reference.h"


#include <QTimer>
#include <QDebug>


Reference::Reference(QObject *parent) :
    ModelItem(parent)
{
}

QString Reference::referencePath() const
{
    if (m_referenceItem.isNull())
    {
        return QString();
    }

    return m_referenceItem->objectName();
}

const ModelItem *Reference::referenceItem() const
{
    return m_referenceItem;
}

QVariant Reference::data(const QString &name) const
{
    if (m_referenceItem.isNull())
    {
        return QVariant();
    }
    return m_referenceItem->property(name.toLatin1());
}

void Reference::setReferencePath(QString arg)
{
    if (m_referencePath != arg)
    {
        m_referencePath = arg;
        emit referencePathChanged(arg);

        if (m_referenceItem.isNull() || m_referenceItem->objectName() == m_referencePath)
        {
            return;
        }

        // reference refreshing need to be delayed until all items in the tree are created.
        QTimer::singleShot(0, this, SLOT(refreshReference()));
    }
}

void Reference::setReferenceItem(ModelItem *item)
{
    if (m_referenceItem.data() != item)
    {
        m_referenceItem = item;
        emit referenceItemChanged();
    }
}

void Reference::setData(const QString &name, const QVariant &value)
{
    setProperty(name.toLatin1(), value);
}

void Reference::refreshReference()
{
    const ModelItem* root = rootItem();
    m_referenceItem = root->findChild<ModelItem*>(m_referencePath);
}


